﻿using Futuret.Core.Futuret;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Future.Shared.Core.Filters;

/// <summary>
///     Author: Riva
///     Date: 2023/7/11 15:12
///     Description: 异常拦截器 拦截 StatusCode>=500 的异常
/// </summary>
public class CustomExceptionFilterAttribute : IAsyncExceptionFilter
{
    private readonly IHttpContextAccessor _contextAccessor;

    public CustomExceptionFilterAttribute(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    /// <summary>
    ///     错误处理
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task OnExceptionAsync(ExceptionContext context)
    {
        await Task.Run(() =>
        {
            var httpContext = _contextAccessor.HttpContext;
            httpContext!.Response.ContentType = "application/json";
            var unifyResponse = new WebResult
            {
                msg = context.Exception.Message,
                code = context.Exception switch
                {
                    FuturetException cloudException => CodeEnum.ProhibitCorresponding,
                    _ => CodeEnum.Error
                }
            };
            httpContext.Response.StatusCode = (int)CodeEnum.Success;
            context.Result = new JsonResult(unifyResponse);
        });
    }
}